
//
//  ForgotPasswordViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/24.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "RegisterViewController.h"
#import "DiscoverListViewController.h"
#import "LoginViewController.h"
#import "LoginAndRegisterTitleView.h"
#import "RegisterProtocolView.h"
#import "HWTFCursorView.h"
#import "UserInfoFollowModel.h"
@interface RegisterViewController ()
/*控件*/
@property (nonatomic,strong)LoginAndRegisterTitleView *titleView;


@property (nonatomic,strong)UILabel *phoneLb;

@property (nonatomic,strong)UIButton *sendBtn;

@property (nonatomic,strong)UIButton *loginBtn;

@property (nonatomic,assign)BOOL status;

@property (nonatomic,strong)UIImageView *loginBackGroundImgView;

@property (nonatomic,strong)UIButton *backButton;

@property (nonatomic,strong)UIView *phoneView;
/// 输入框
@property (nonatomic,strong)UITextField *phoneTF;

@property (nonatomic,strong)UILabel *placeLb;

@end

@implementation RegisterViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;

}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;
    
    [self setUI];
    
    // Do any additional setup after loading the view.
}


#pragma mark - setUI
- (void)setUI{
    
    [self.view addSubview:self.loginBackGroundImgView];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.phoneLb];
    [self.view addSubview:self.sendBtn];
    [self.view addSubview:self.phoneView];
    [self.view addSubview:self.phoneTF];
    [self.view addSubview:self.placeLb];
    [self.view addSubview:self.loginBtn];
    
    self.loginBackGroundImgView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(16 + GK_STATUSBAR_HEIGHT);
        make.left.equalTo(self.view.mas_left).offset(16);
    }];
    
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLb.mas_bottom).offset(40);
        make.height.mas_equalTo(44);
        make.right.equalTo(self.view.mas_right).offset(-16);
        make.left.equalTo(self.view.mas_left).offset(16);
    }];
    
    [self.placeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.phoneView);
        make.left.equalTo(self.phoneView).offset(20);
    }];
    
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.phoneView).offset(20);
        make.centerY.equalTo(self.phoneView);
        make.right.equalTo(self.phoneView.mas_right).offset(-20);
    }];
    
    
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backButton.mas_bottom).offset(28);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left).offset(24);
    }];
   
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView.mas_bottom).offset(5);
        make.right.equalTo(self.view.mas_right).offset(-16);
    }];
    
    [self.phoneLb mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(16);
        }else{
            make.left.equalTo(self.view.mas_left).offset(16);
        }
        make.centerY.equalTo(self.sendBtn);
    }];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneView.mas_bottom).offset(24);
        make.height.mas_equalTo(44);
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-16);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(16);
        }else{
            make.left.equalTo(self.view).offset(16);
            make.right.equalTo(self.view).offset(-16);
        }
    }];

    self.sendBtn.enabled = NO;
   
    [self setStartTimer];
    

}

- (void)setStartTimer{
    __block NSInteger time = 59;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(timer, ^{
        if (time <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.sendBtn.enabled = YES;
                [self.sendBtn setTitle:@"重新发送" forState:UIControlStateNormal];
            });
        }else{
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sendBtn setTitle:[NSString stringWithFormat:@"%.2d秒",seconds] forState:UIControlStateDisabled];
                self.sendBtn.enabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(timer);
}

#pragma mark - action
- (void)sendMethod{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.phoneStr;
    param[@"md5"] = [RPAppManager md5StrWithApi:SendCode];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SendCode) parames:param success:^(id responseObj) {
        __block NSInteger time = 59;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (time <= 0) {
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.sendBtn.enabled = YES;
                    [self.sendBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                });
            }else{
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.sendBtn setTitle:[NSString stringWithFormat:@"%.2d秒",seconds] forState:UIControlStateDisabled];
                    self.sendBtn.enabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(timer);
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loginMethod{
    [SVProgressHUD show];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.phoneStr;
    param[@"code"] = self.phoneTF.text;
    param[@"md5"] = [RPAppManager md5StrWithApi:UserRegister];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UserRegister) parames:param success:^(id responseObj) {
        // 请求用户登录信息
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = responseObj[RESPONSE][@"id"];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUser];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUser) parames:param success:^(id responseObj) {
            
            UserInfoModel *userInfo = [UserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            [userInfo save];
            
            [MobClick profileSignInWithPUID:userInfo.id.stringValue];
            // 获取用户关联关注列表
            [self getUserFollowListSource];
                    
        } failure:^(NSError *error) {
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
        
        }];

    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
        //[WHToast showErrorWithMessage:error.userInfo[@"info"] originY:0 duration:2 finishHandler:nil];
        
        self.loginBtn.selected = YES;
        
    }];
}

- (void)getUserFollowListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetFollowList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetFollowList) parames:param success:^(id responseObj) {

        NSArray *resultArray = [UserInfoFollowModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        
        // 获取数据库单例对象
        RLMRealm *realm = [RLMRealm defaultRealm];
        // 更新当前登录这样用户的信息
        [realm transactionWithBlock:^{
            [realm addOrUpdateObjects:resultArray];
        }];
        
        __weak typeof(self)weakSelf = self;
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"登录成功" originY:0 duration:1 finishHandler:^{
            
            [[NSUserDefaults standardUserDefaults]setObject:self.phoneStr forKey:self.phoneStr];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            if (weakSelf.isAppLogin) {
                DiscoverListViewController *vc = [[DiscoverListViewController alloc]init];
                NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:vc];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
            }else{
                __block NSInteger index = -1;
                [weakSelf.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isKindOfClass:[LoginViewController class]]) {
                        index = idx;
                        *stop = YES;
                    }
                }];
                
                if (index != -1) {
                    [weakSelf.navigationController popToViewController:weakSelf.navigationController.viewControllers[index - 1] animated:NO];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoSource" object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoUseage" object:nil];
                    // 发送通知 刷新页面按钮状态
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLoginUserInfoFollowListStatus" object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateRefreshToken" object:nil];
                }
            }
            [MobClick event:@"login_phone"];
        }];

    } failure:^(id error) {

    }];
}



- (LoginAndRegisterTitleView *)titleView{
    if (!_titleView) {
        _titleView = [[LoginAndRegisterTitleView alloc]initWithMainTitle:@"验证码已发送至" andSubTitle:@""];
    }
    return _titleView;
}

- (UIButton *)sendBtn{
    if (!_sendBtn) {
        _sendBtn = [[UIButton alloc]init];
        [_sendBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateDisabled];
        [_sendBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateNormal];
        [_sendBtn addTarget:self action:@selector(sendMethod) forControlEvents:UIControlEventTouchUpInside];
        _sendBtn.titleLabel.font = font(14);
    }
    return _sendBtn;
}
- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc]init];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_normal_tag"] forState:UIControlStateNormal];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_selected_tag"] forState:UIControlStateSelected];
        [_loginBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateNormal];
        [_loginBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateSelected];
        
        [_loginBtn addTarget:self action:@selector(loginMethod) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.enabled = NO;
    }
    return _loginBtn;
}
- (UILabel *)phoneLb{
    if (!_phoneLb) {
        _phoneLb = [[UILabel alloc]init];
        _phoneLb.text = self.phoneStr;
        _phoneLb.font = font(14);
        _phoneLb.textColor = [UIColor whiteColor];
    }
    return _phoneLb;
}
- (UILabel *)placeLb{
    if (!_placeLb) {
        _placeLb = [[UILabel alloc]init];
        _placeLb.text = @"请输入短信验证码";
        _placeLb.textColor = RGBA(204, 204, 204, 1);
        _placeLb.font = font(14);
    }
    return _placeLb;
}

- (UITextField *)phoneTF{
    if (!_phoneTF) {
        _phoneTF = [[UITextField alloc]init];
        _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
        [_phoneTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        _phoneTF.returnKeyType = UIReturnKeyDone;
        _phoneTF.textColor = [UIColor whiteColor];
        _phoneTF.font = font(14);
        [_phoneTF becomeFirstResponder];
        
        if (@available(iOS 12.0, *)) {
            _phoneTF.textContentType = UITextContentTypeOneTimeCode;
        } else {
            // Fallback on earlier versions
        }
    }
    return _phoneTF;
}

- (UIView *)phoneView{
    if (!_phoneView) {
        _phoneView = [[UIView alloc]init];
        _phoneView.backgroundColor = RGBA(255, 255, 255, 0.2);
        _phoneView.layer.cornerRadius = 22;
        _phoneView.layer.masksToBounds = YES;
    }
    return _phoneView;
}

- (UIImageView *)loginBackGroundImgView{
    if (!_loginBackGroundImgView) {
        _loginBackGroundImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_backgroud_tag"]];
    }
    return _loginBackGroundImgView;
}

- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [[UIButton alloc]init];
        [_backButton setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

#pragma mark - textFieldDelegate
- (void)textDidChange:(UITextField *)textField{

    self.placeLb.hidden = textField.text.length > 0;
    
    if ([textField.text isSpaceString] && textField.text.length > 0) {
        
        return;
    }
    
    self.loginBtn.enabled = textField.text.length > 0;

    if(textField.text.length > 6){
        textField.text = [textField.text substringToIndex:6];
        return;
    }
    
    if (textField.text.length == 0) {

        self.loginBtn.selected = NO;
    }else{
        self.loginBtn.selected = YES;
    }
}
#pragma mark - other
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

@end
